package com.mapfinal.data.shpfile;

import java.awt.Color;
import java.io.File;
import java.nio.charset.Charset;

import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.styling.SLD;
import org.geotools.styling.SLDParser;
import org.geotools.styling.Style;
import org.geotools.styling.StyleFactory;

import com.jfinal.kit.StrKit;

public class ShapefileKit {

	public static Layer createLayer(String shpfile, String sldfile) {
		try {
			// 数据文件的加载
			File file = new File(shpfile);
			ShapefileDataStore shpDataStore = null;
			shpDataStore = new ShapefileDataStore(file.toURI().toURL());
			// 设置编码
			Charset charset = Charset.forName("GBK");
			shpDataStore.setCharset(charset);
			String typeName = shpDataStore.getTypeNames()[0];
			SimpleFeatureSource featureSource = null;
			featureSource = shpDataStore.getFeatureSource(typeName);

			// 样式文件的加载
			Style style = SLD.createSimpleStyle(featureSource.getSchema());
			if (StrKit.notBlank(sldfile)) {
				// SLD的方式
				File sldFile = new File(sldfile);
				StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory();
				SLDParser stylereader = new SLDParser(styleFactory, sldFile.toURI().toURL());
				Style[] stylearray = stylereader.readXML();
				style = stylearray[0];
			} else {
				SLD.setPolyColour(style, Color.RED);
			}

			// 承载数据文件及样式文件的Layer
			Layer layer = new FeatureLayer(featureSource, style);

			return layer;
			// System.out.println("add map layer : " + shpPath);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
